import type { Recordable } from '@vben/types';

import { StorageManager } from '@vben-core/shared/cache';

import { debounce } from 'lodash-es';

// 列宽退拽临时存储，刷新页面后仍然有效
export class ColumnSizeSaver {
  save: (key: string, size: number) => void;
  private cache: null | StorageManager = null;
  constructor() {
    const env = import.meta.env.PROD ? 'prod' : 'dev';
    const appVersion = import.meta.env.VITE_APP_VERSION;
    const namespace = `${import.meta.env.VITE_APP_NAMESPACE}-${appVersion}-${env}-fs-crud`;
    this.cache = new StorageManager({ prefix: namespace });

    this.save = debounce((key: string, size: number) => {
      const saveKey = this.getKey();

      let data = this.cache?.getItem<Recordable>(saveKey);
      if (!data) {
        data = {};
      }
      data[key] = size;

      this.cache?.setItem(saveKey, data);
    });
  }
  clear() {
    const saveKey = this.getKey();
    this.cache?.removeItem(saveKey);
  }
  get(key: string) {
    const saveKey = this.getKey();
    const row = this.cache?.getItem<Recordable>(saveKey);
    return row?.[key];
  }
  getKey() {
    const loc = window.location;
    const currentUrl = `${loc.pathname}${loc.search}${loc.hash}`;
    return `columnSize-${currentUrl}`;
  }
}

export const columnSizeSaver = new ColumnSizeSaver();
